const Base = require("./base.js");
/*登录*/
module.exports = class extends Base {
  async indexAction() {
    let ip = "";
    const equipmentCoding = this.post("equipmentCoding") //设备编码
    try {
      ip = this.ctx.header["x-real-ip"] || "127.0.0.1";
    } catch (e) {
      ip = "127.0.0.1";
    }
    let res = await this.model("administrator")
      .where({
        userNmae: this.post("name"),
        userPassword: this.post("paw"),
      })
      .find();
    if (!res.id) {
      return this.fail("用户名或密码错误");
    }
    if (equipmentCoding && res.CharacterNameCode == 53) {
      try {
        const yxq = new Date()
        yxq.setTime(res.AccountValidityPeriod)
        const dq = new Date()
        console.log(yxq.getTime()+'666666'+ dq.getTime());
        if(dq.getTime()>yxq.getTime()){
          return this.fail("账号已过期，请联系管理员");
        }
      } catch (e) {
console.log('111111');
      }
      if (!res.equipmentCoding) {
        await this.model("administrator")
          .where({
            id: res.id
          })
          .update({
            equipmentCoding
          });
      } else {
        if (res.equipmentCoding != equipmentCoding) {
          return this.fail("该账号已绑定设备");
        }
      }
    }

    let CharacterNameCode = res.CharacterNameCode;
    let NameCode = res.CharacterNameCode;
    if (res.accountType == 1) {
      let groupmanagement = await this.model("groupmanagement")
        .where({
          id: res.CharacterNameCode,
        })
        .find();
      CharacterNameCode = groupmanagement.type;
    }
    let rolemanagement = await this.model("rolemanagement")
      .where({
        id: CharacterNameCode,
      })
      .find();

    let city = ""
    try {
      const { content } = await this.dxGet("https://api.map.baidu.com/location/ip?ak=Vv4btjr4PQrpGIYG4XO6j7TnDCWgoOyO&coor=bd09ll&ip=" + ip)
      city = content.address
    } catch (e) {

    }
    await this.model("administrator")
      .where({ id: res.id })
      .update({
        loadIp: ip,
        city
      });
    res.loadIp = ip;
    this.success({
      token: this.generateTheToken(res),
      userNmae: res.userNmae,
      userNickname: res.userNickname,
      headPortrait: res.headPortrait,
      CharacterNameCode: res.CharacterNameCode,
      accountType: res.accountType,
      NameCode,
      ...rolemanagement,
      userId: res.id,
      secretKeytoken: this.config("secretKeytoken"),
    });
  }
};
